<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\BuilderPlus\components\Button as Btn;
use addons\BuilderPlus\components\Column as Col;
use addons\BuilderPlus\components\Edit;
use addons\BuilderPlus\components\Search;
use addons\BuilderPlus\facade\Table;
use app\common\model\Relation;
use app\common\tool\Result;
use think\facade\View;
use think\Response;
use app\common\model\Assets;
use app\common\model\Level;
use app\common\model\Logs;


class User extends Base
{

    public function getOptions(): array
    {
        return [
            'pk'       => 'id',
            'model'    => \app\common\model\User::class,
            'with'     => ['level', 'assets'],
            'validate' => \app\admin\validate\User::class,
            'fast'     => [
                'save' => '_save',
                'edit' => 'user/edit'
            ]
        ];
    }

    public function index($is_active = 1): string
    {

        $table = Table::init($this)
            ->addColumns([
                ['id', 'ID', fn(Col $col) => $col->width(80)],
                ['photo', '头像', fn($col) => $col->width(80)->lazyImage()],
                ['code', '会员编号', '', fn(Edit $edit) => $edit->type(1)->require()],
                ['nickname', '会员昵称', '', fn(Edit $edit) => $edit->require()],
                ['mobile', '手机号', '', fn(Edit $edit) => $edit->number()->require()],
                ['level_id', '会员级别', fn($col) => $col->templet('{{d.level?d.level.title:"暂无"}}'),
                    fn(Edit $edit) => $edit->select(Level::column('title', 'id'))],
                ['parent_code', '推荐人', '', fn(Edit $edit) => $edit->type(1)->require()],
            ]);

        foreach (Assets::getFields(3) as $field => $title) {
            $table->addColumn($field, $title, fn(Col $col) => $col->withSort('assets')->templet('{{d.assets.' . $field . '}}'));
        }

        return $table
            ->addColumns([
                ['password', '登录密码', fn($col) => $col->hide(), fn(Edit $edit) => $edit->type(1)->password()],
                ['pay_password', '支付密码', fn($col) => $col->hide(), fn(Edit $edit) => $edit->type(1)->password()],
                ['my_total', '个人业绩', fn($col) => $col->sort()],
                ['team_total', '团队业绩', fn($col) => $col->sort()],
                ['create_time', '注册时间', fn($col) => $col->width(140)],
                $is_active == 2 ? ['active_time', '激活时间', fn($col) => $col->width(140)] : [],
                ['is_lock', '锁定', fn($col) => $col->switch('锁定|正常', '1|0')->fixed('right')]
            ])
            ->addTopButtons([
                'add',
                'password'     => fn(Btn $btn) => $btn->title('重置登录密码')
                    ->icon('layui-icon-leaf')
                    ->class('danger')
                    ->url(url('user/reset')->build())
                    ->placeholder('默认密码111111')
                    ->event('prompt'),
                'pay_password' => fn(Btn $btn) => $btn->title('重置支付密码')
                    ->icon('layui-icon-leaf')
                    ->class('danger')
                    ->url(url('user/reset')->build())
                    ->placeholder('默认密码222222')
                    ->event('prompt'),
            ])
            ->addRightButtons([
                'login' => fn($btn) => $btn->title('登录')->url(url('user/login')->build())->customEvent('login'),
                'edit',
                $is_active == 1 ? 'delete' : ''
            ], $is_active == 1 ? 180 : 130)
            ->addSearch([
                ['code__nickname__mobile', '会员编号/昵称/手机号', fn(Search $search) => $search->condition('Like')],
                ['create_time', '注册时间', fn(Search $search) => $search->type('date')],
                $is_active == 2 ? ['active_time', '激活时间', fn(Search $search) => $search->type('date')] : []
            ])
            ->setSortType([$is_active == 1 ? 'create_time' : 'active_time' => 'desc'])
            ->specifyQuery([['is_active', '=', $is_active]])
            ->enableExport()
            ->fetch();
    }


    public function choose(): string
    {
        return Table::init($this)
            ->setCheckbox(false)
            ->addColumns([
                ['id', 'ID', fn(Col $col) => $col->width(80)],
                ['photo', '头像', fn($col) => $col->width(80)->lazyImage()],
                ['code', '会员编号'],
                ['nickname', '会员昵称'],
                ['mobile', '手机号'],
                ['create_time', '注册时间', fn($col) => $col->minWidth(140)],
                ['btn', '操作', fn($col) => $col->width(100)->templet('<a class="layui-btn layui-btn-sm">选择</a>')->fixed('right')],
            ])
            ->addSearch([
                ['code__nickname__mobile', '会员编号/昵称/手机号', fn(Search $search) => $search->condition('Like')],
                ['create_time', '注册时间', fn(Search $search) => $search->type('date')->dateType('datetime')]
            ])
            ->fetch();
    }


    public function reset(): Response
    {
        try {
            $param = $this->request->post();

            if (isset($param['password'])) {
                $key = 'password';
                $value = md5($param['password'] ?: '111111');
                $name = '登录密码';
            } else {
                $key = 'pay_password';
                $value = md5($param['pay_password'] ?: '222222');
                $name = '支付密码';
            }
            $this->model::update([$key => $value], ['id' => explode(',', $param['id'])]);
            $msg = '重置了【' . $name . '】会员标识ID【' . $param['id'] . '】';
            Logs::adds($msg, $this->admin->id, $this->admin->admin_name);
            return Result::success('已重置');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }


    public function login(): Response
    {
        try {
            $user = $this->model::where('id', $this->request->post('id'))->find();
            if ($user->token) {
                $token = $user->token;
            } else {
                $token = md5(time() . json_encode($user));
                $user->token = $token;
                $user->save();
            }
            cookie('token', $token);
            $description = '登录操作，会员【' . $user->code . '】';
            Logs::adds($description, $this->admin['id'], $this->admin['admin_name']);
            return Result::fastReturn(['code' => 1, 'msg' => '登录成功', 'data' => ['code' => $user->code, 'url' => '/']]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    public function recharge(): Response|string
    {
        $param = $this->request->param();
        if (!empty($param['type'])) {
            switch ($param['type']) {
                case "get":
                    $user = $this->model::whereLike('code|mobile|nickname', '%' . $param['val'] . '%')
                        ->field('id,code,mobile,nickname')->select();
                    return Result::success('success', $user, 0);
                case "account":
                    $assets = Assets::where('uid', $param['id'])->value($param['val']);
                    if ($assets) {
                        return Result::fastReturn(['code' => 1, 'msg' => '', 'result' => $assets]);
                    } else {
                        return Result::fail('加载失败');
                    }
                case "save":
                    try {
                        validate(\app\admin\validate\Recharge::class)->check($param);
                        return Result::fastReturn($this->model::recharge($param, $this->admin));
                    } catch (\Exception $e) {
                        return Result::fail($e->getError());
                    }

                default:
                    return Result::fail('加载失败');
            }
        }
        View::assign('assets', Assets::getFields(3));
        return View::fetch();
    }

    public function delete(): Response
    {
        try {
            $user = $this->model::where('id', $this->request->post($this->getOptions()['pk']))->find();
            if (empty($user)) {
                return Result::fail('会员不存在');
            }
            if ($user->is_active == 2) {
                return Result::fail('会员已激活，无法删除');
            }
            $count = Relation::where('uid', $user->id)->count();
            if ($count) {
                return Result::fail('该会员已推荐会员无法删除');
            }
            Relation::destroy(['new_uid' => $user->id], true);
            $this->model::destroy(['id' => $user->id], true);

            Logs::adds('删除会员【' . $user->code . '】', $this->admin->id, $this->admin->admin_name);
            return Result::success('已删除');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }

}
